<?php


namespace app\common\service;

// 处理业务

use app\common\model\Admin;
use app\common\model\Order as OrderModel;
use app\common\model\OrderExpress;
use app\common\model\Vcode;
use plug\SHttp;
use plug\SUtil;
use plug\SConstant;


class ServiceAdmin extends ServiceBase
{

	function getAdmin($user_name){
        $adminModel = new Admin();
        $where = [
            'user_name'=>$user_name,
            'status'=>1,
        ];
        // 查询用户所有信息
        $info = $adminModel->field('user_id')->where($where)->find();
        if(!$info){
            return [];
        }
        return $info->toArray();
	}

    // 以用户名查询 用户是否正确
    function Getuser_name ($user_name, $user_pass, $vcode, $type) {
        $adminModel = new Admin();
        $where = [
            'user_name'=>$user_name,
            'status'=>1,
        ];
        // 查询用户所有信息
        $userArr = $adminModel->getOne($where,'user_id,user_name,group_id,user_pass,pass_random,lock_note,status,spf_id,sbg_id');

        if(!$userArr){//状态异常是被锁定了
            //写入登录日志
            $this->setError(-1, '用户账号异常，请联系客服');
            return false;
        }
        if($type == 1){
            // 密码登录
            $password = SUtil::getHashBackend($user_pass, $userArr['pass_random']);
            if((!$userArr || ($password !== $userArr['user_pass']))){
                $this->setError(-1, "密码错误");
                return false;
            }
        }elseif($type == 2){
            //查看验证码是否错误
            $vcodeModel = new Vcode();
            $res = $vcodeModel->CheckVcode($user_name,$vcode);
            if(!$res){
                $this->setError(-1, '验证码错误或者过期，请重新发送1');
                return false;
            }
        }else{
            //查看验证码是否错误
            $vcodeModel = new Vcode();
            $res = $vcodeModel->CheckVcode($user_name,$vcode);
            if(!$res){
                $this->setError(-1, '验证码错误或者过期，请重新发送');
                return false;
            }

        }
        // 登录成功
        $pass_random = $this->update_login($userArr['user_id'],$user_pass);
        //写cookie
        $loginInfo = array(
            'admin_userid' => $userArr['user_id'],
            'admin_user_name' => $userArr['user_name'],
            'admin_userkey' => md5($userArr['user_id'] . $userArr['user_name'] . $userArr['group_id'] . SConstant::ADMINUSERKEY . $pass_random)
        );
        $expireTime = 3600 * 24 * 7;

        // 设置
        cookie('name', $loginInfo, $expireTime);
        return true;
    }

    /**
     * 更新用户登录成功的信息
     */
    public function update_login($userid,$user_pass=''){
        $adminModel = new Admin();

        if(empty($userid)){
            return false;
        }
        $where = ['user_id' => $userid];

        $loginSucInfo = array(
            'last_time'=>time(),
            'last_ip'=>SUtil::getIp()
        );
        if($user_pass){
            $loginSucInfo['pass_random'] = SUtil::random(6,0);
            $loginSucInfo['user_pass'] = SUtil::getHashBackend($user_pass, $loginSucInfo['pass_random']);
        }
        $re = $adminModel->getUpdate($where, $loginSucInfo);
        if($re==false||!$loginSucInfo['pass_random']){//未更新成功或者未更新pass_random那么返回原来的sn
            $one = $adminModel->getOne($where,'pass_random');
            $loginSucInfo['pass_random'] = $one['pass_random'];
        }
        return $loginSucInfo['pass_random'];
    }

    // 处理添加管理用户
    public function DealAdmin($params)
    {
        $adminModel = new Admin();

        // 取出用户ID
        $user_id = $params['user_id'];
        // 去除数组中的user_id
        unset($params['user_id']);

        // 判断密码是否为空
        if(!empty($params['user_pass'])){
            $user_pass = $params['user_pass'];
        }else{
            // 默认密码
            $user_pass = "456789";
        }

        if(!empty($params['spf_id'])){
            $params['spf_id'] = $params['spf_id'];
        } else {
            $params['spf_id'] = '0';
        }

        // 密码随机验证码
        $params['pass_random'] = SUtil::random(6,0);
        // 生成密码
        $params['user_pass'] = SUtil::getHashBackend($user_pass, $params['pass_random']);
        // 创建时间戳
        $params['add_time'] = time();

        $rs = $adminModel->edit($params, $user_id);
        if($rs === false){
            $this->setError("-1",$adminModel->getError());
            return false;
        }
        return $rs;
    }


//
//    /**
//     * 查询快递接口
//     * @param string $com   快递公司编码
//     * @param string $num   快递单号
//     * @param string $phone 手机号
//     * @param int $orderId  订单ID
//     * @param int $type     类型：1-没有数据、2-有数据
//     */
//    public function CheckExpress($com = "", $num = "", $phone = "", $orderId = 0, $type = 1)
//    {
//
//        $OrderExpress = new OrderExpress();
//
//        $key = 'PPouFJQR3601';                        // 客户授权key
//        $customer = '5F6DBDD708A91FE1098353F80794B666';                   // 查询公司编号
//        $param = array (
//            'com' => $com,             // 快递公司编码
//            'num' => $num,     // 快递单号
//            'phone' => $phone,                // 手机号
//            'from' => '',                 // 出发地城市
//            'to' => '',                   // 目的地城市
//            'resultv2' => '1',            // 开启行政区域解析
//            'show' => '0',                // 返回格式：0：json格式（默认），1：xml，2：html，3：text
//            'order' => 'desc'             // 返回结果排序:desc降序（默认）,asc 升序
//        );
//
//        //请求参数
//        $post_data = array();
//        $post_data['customer'] = $customer;
//        $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
//        $sign = md5($post_data['param'].$key.$post_data['customer']);
//        $post_data['sign'] = strtoupper($sign);
//
//        $url = 'https://poll.kuaidi100.com/poll/query.do';    // 实时查询请求地址
//
//        // 发送post请求
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_POST, 1);
//        curl_setopt($ch, CURLOPT_HEADER, 0);
//        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//        $result = curl_exec($ch);
//
//        // 第二个参数为true，表示格式化输出json
////        $data = json_decode($result, true);
////        echo "<pre>";
////        var_dump($data);die;
//
////        var_dump($result);
////        $data = json_decode($result, true);
////        $data = json_decode($result, true);
//
//        if($type == 1){
//            // 没数据
//            $order_express_data = [
//                'order_id' => $orderId,
//                'check_time'    => time(),
//                'result'    => $result
//            ];
//            $rs = $OrderExpress->save($order_express_data);
//        }elseif($type == 2){
//            // 有数据
//            $order_express_data = [
//                'check_time'    => time(),
//                'result'    => $result
//            ];
//            $rs = $OrderExpress->where('order_id', $orderId)->update($order_express_data);
//        }
//        if($rs === false){
//            return false;
//        }else{
//            return true;
//        }
//    }


    /**
     * 查询快递接口
     * @param $orderId
     * @return false|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function CheckExpress($orderId)
    {
        // 订单快递数据
        $orderModel = new OrderModel();
        $order_data = $orderModel->alias('o')->field('o.order_status,o.express_id,o.tracking_number,o.r_phone,e.express_name,e.express_code')->where(['order_id' => $orderId])->leftJoin([
            ['ddt_express e','o.express_id=e.express_id'],
        ])->find();
        if ($order_data['order_status'] != 3 && $order_data['order_status'] != 4) {
            $this->setError(-1,'未发货');
            return false;
        }


        $OrderExpress = new OrderExpress();
        $orderexpress_data = $OrderExpress->getOne(['order_id' => $orderId]);
        if($orderexpress_data && calculate([time(), $orderexpress_data['check_time']], '-') <= 3600){
            $result = json_decode($orderexpress_data['result'],true);
            return [
                'list'=>$result['data'],
                'message'=>$result['message'],
                'express_name'=>$order_data['express_name']
            ];
        }

        //判断物流信息是否过期，过期就查询一边
        $key = 'PPouFJQR3601';                        // 客户授权key
        $customer = '5F6DBDD708A91FE1098353F80794B666';                   // 查询公司编号
        $param = array (
            'com' => $order_data['express_code'],             // 快递公司编码
            'num' => $order_data['tracking_number'],     // 快递单号
            'phone' => $order_data['r_phone'],                // 手机号
            'resultv2' => 1,
            'order' => 'desc'             // 返回结果排序:desc降序（默认）,asc 升序
        );

        //请求参数
        $post_data = [
            'customer'=>$customer,
            'param'=>json_encode($param)
        ];
        //生成签名
        $sign = md5($post_data['param'].$key.$post_data['customer']);
        $post_data['sign'] = strtoupper($sign);
        $url = 'https://poll.kuaidi100.com/poll/query.do';    // 实时查询请求地址
        // 发送post请求
        $result = SHttp::http_curl($url,http_build_query($post_data),[],'post');

        $data = json_decode($result['str'],true);
        if($data['message'] != 'ok'){
            $this->setError(-1,$data['message']);
            return false;
        }

        if($orderexpress_data){
            $rs = $OrderExpress->save([
                'check_time'    => time(),
                'result'    => json_encode($data),
            ],[
                'order_id'=>$orderId,
            ]);
            if(!$rs){
                $this->setError(-1,$OrderExpress->getError());
                return false;
            }
        }
        if(!$orderexpress_data){
            $rs = $OrderExpress->save([
                'order_id'    => $orderId,
                'check_time'    => time(),
                'result'    => json_encode($data),
            ]);
            if(!$rs){
                $this->setError(-1,$OrderExpress->getError());
                return false;
            }
        }
        return [
            'list'=>$data['data'],
            'message'=>$data['message'],
            'express_name'=>$order_data['express_name']
        ];
    }

}